package com.example.recipes;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.zookeeper.CreateMode;

import java.util.concurrent.TimeUnit;

/**
 * @author Creared by wangyang on 2019-01-29 11:02
 * email:techyang.wangy.@ymm56.com
 */
public class PathChildrenCacheSample {

    static String path = "/zk-book/pathchildrencache";
    static CuratorFramework client = CuratorFrameworkHolder.CURATOR_FRAMEWORK;

    public static void main(String[] args) throws Exception {
        client.start();

        PathChildrenCache pcc = new PathChildrenCache(client, path, true);
        pcc.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        pcc.getListenable().addListener((curatorFramework, event) -> {
            switch (event.getType()) {
                case CHILD_ADDED:
                    System.out.println("Child added, data:" + event.getData() + ", type:" + event.getType());
                    break;
                case CHILD_UPDATED:
                    System.out.println("Child updated, data:" + event.getData() + ", type:" + event.getType());
                    break;
                case CHILD_REMOVED:
                    System.out.println("Child removed, data:" + event.getData() + ", type:" + event.getType());
                    break;
                default:
                    break;
            }
        });
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path);
        TimeUnit.SECONDS.sleep(1);
        client.create().forPath(path + "/c1");
        TimeUnit.SECONDS.sleep(1);
        client.delete().forPath(path + "/c1");
        TimeUnit.SECONDS.sleep(1);
        client.delete().deletingChildrenIfNeeded().forPath(path);
        TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
    }
}
